﻿using System;
using System.Collections.Generic;

using System.Text;
using TimKen.DataEntity;

namespace TimKen.BussLogic
{
    /// <summary>
    /// 用户帐户操作类。两种类别的帐户操作需要整合。
    /// </summary>
    public class UserFacade
    {
        static UserAccountManager uam = new UserAccountManager();
        static WebUserManager wum = new WebUserManager();
        /// <summary>
        /// 用户是否存在
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static bool Exists(string userName)
        {
            bool result = false;
            if (uam.Exists(userName) || wum.Exists(userName))
            {
                result = true;
            }
            return result;
        }

        public static UserS Login(string userName, string password)
        {
            UserS u = null;
            u = uam.Login(userName, password);
            if (u != null)
            {
                UserAccount user = u as UserAccount;
                if (user.RoleID == 2)
                    u.UserType = UserType.FactoryBuyer;
                else if (user.RoleID == 1)
                    u.UserType = UserType.DataAdministrator;
                else if (user.RoleID == 3)
                    u.UserType = UserType.FactoryFinance;
                else
                {
                    u.UserType = UserType.SystemAdministrator;
                }
                u.IsValid = true;
                return u;
            }
            u = wum.Login(userName, password);
            if (u != null)
            {
                u.UserType = UserType.SelfRegistered;
                return u;
            }
            return null;
        }

        public static bool CheckUserPasswordExpired(UserS user)
        {
            if (user.UserType == UserType.Viewer || user.UserType == UserType.SelfRegistered)
                return false;
            UserAccount ua = user as UserAccount;
            if (ua.LastUpdatePwd.Value.AddDays(SystemConfigManager.SystemConfig.PasswordExpired).CompareTo(DateTime.Now) > 0)
                return true;
            return false;
        }

        public static UserS GetUser(string userName)
        {
            UserS u = null;
            u = uam.GetModel(userName);
            if (u != null)
            {
                return u;
            }
            u = wum.GetModel(userName);
            if (u != null)
            {
                return u;
            }
            return null;
        }


    }
}
